import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Select, Input, Checkbox } from 'antd';
import ConfigTable from '../../../../components/configTable';
import { TYPE_OPTIONS } from '../../../../../../utils/constant';

const EnterParam = forwardRef((props, ref) => {
  const { value } = props;
  const [data, setData] = useState([]);

  const defaultData = {
    name: '',
    type: 0,
    nonEmpty: 1,
    desc: '',
  };

  useEffect(() => {
    value.params && setData(value.params);
  }, [value.params]);

  useImperativeHandle(ref, () => ({
    getData: () => {
      data.length &&
        data.forEach((item) => {
          if (!item.name) throw '请输入入参名!';
        });
      return data;
    },
  }));

  const handleChange = (value, index, key) => {
    const temp = [...data];
    if (key === 'name') {
      const new_value = value.match(/[0-9a-zA-Z_.]{1,}/);
      temp[index][key] = new_value ? new_value[0] : '';
      return setData(temp);
    }
    temp[index][key] = value;
    setData(temp);
  };

  const cusColumns = [
    {
      title: '参数名',
      dataIndex: 'name',
      render: (text, _, index) => (
        <Input
          value={text}
          maxLength={30}
          placeholder='请输入'
          onChange={(e) => handleChange(e.target.value, index, 'name')}
        />
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (text, _, index) => (
        <Select placeholder='请选择' value={text} onChange={(value) => handleChange(value, index, 'type')}>
          {TYPE_OPTIONS.map((item, index) => (
            <Select.Option value={index} key={index}>
              {item}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '必填',
      dataIndex: 'nonEmpty',
      render: (text, _, index) => (
        <Checkbox checked={!text} onChange={(e) => handleChange(e.target.checked ? 0 : 1, index, 'nonEmpty')} />
      ),
    },
    {
      title: '描述',
      dataIndex: 'desc',
      render: (text, _, index) => (
        <Input
          value={text}
          maxLength={256}
          placeholder='不超过256字符'
          onChange={(e) => handleChange(e.target.value, index, 'desc')}
        />
      ),
    },
  ];

  return <ConfigTable data={data} onChange={setData} cusColumns={cusColumns} defaultData={defaultData} />;
});
export default EnterParam;
